<?php
namespace App\Services\Front;

use Illuminate\Support\Facades\DB;

class IndexService extends BaseService
{
    /**
     * 服务类，写复杂的逻辑
     */

    /**
     * 已用列表
     * @param $pages 分页
     * @param $showCode 显示编号
     */
    public function usedCodeList($pages, $showCode='')
    {
        $this->makeEmpty();
        $start = $pages['start'] * $pages['limit'];
        $db = $this->dbConn($this->dbQr)
            ->where('tmp_id', '>', 0);
        if ($showCode) {
            $db = $db->where('show_code', 'like', '%'.$showCode.'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $k => $v) {
            $v = (array) $v;
            $ewmLink = env('DOMAIN').'/h5/?code='.$v['code'];
            $visitNum = $this->dbConn($this->dbQrlog)->where('code', $v['code'])->count();
            $arys[] = [
                'id' => $v['id'],
                'code' => $v['code'],
                'show_code' => $v['show_code'],
                'visit_total' => $visitNum,
                'ewmLink' => $ewmLink,
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 空码列表
     * @param $pages 分页
     * @param $showCode 显示编号
     */
    public function emptyList($pages, $showCode='')
    {
        $this->makeEmpty();
        $db = $this->dbConn($this->dbQr)->where('tmp_id', 0);
        if ($showCode) {
            $db = $db->where('show_code', 'like', '%'.$showCode.'%');
        }
        $total = $db->count();
        $res = $db->skip($pages['start'])->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $k => $v) {
            $v = (array) $v;
            $ewmLink = env('DOMAIN').'/h5/?code='.$v['code'];
            $arys[] = [
                'id' => $v['id'],
                'code' => $v['code'],
                'show_code' => $v['show_code'],
                'ewmLink' => $ewmLink,
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }
}